package com.chrray.position.mygenerator.htmlutil;

import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.*;
import java.util.Map;


public class StringUtils {
	/**
	 * 读取txt文件的内容
	 *
	 * @param file
	 *            读取的文件对象
	 */
	public static String readTxt2String(File file) {
		StringBuilder result = new StringBuilder();
		BufferedReader br = null;
		try {
			br = new BufferedReader(new FileReader(file));// 构造一个BufferedReader类来读取文件
			String s = null;
			while ((s = br.readLine()) != null) {// 使用readLine方法，一次读一行
				result.append(System.lineSeparator() + s);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return result.toString();
	}

	/**
	 * 保存为文件
	 *
	 * @param filePath
	 *            保存的文件地址
	 * @param content
	 *            内容
	 */
	public static void saveToFile(String filePath, String content) {
		PrintStream ps = null;
		try {
			File file = new File(filePath);
			FileOutputStream f = new FileOutputStream(file);
			ps = new PrintStream(f);
			ps.println(content);// 往文件里写入字符串
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
			if (ps != null) {
				ps.flush();
				ps.close();
			}
		}
	}

	/**
	 * 生成html
	 */
	public static void gen(Map<String, Object> mateDate, String tempFile, String genFile) throws Exception {
		Configuration config = new Configuration();
		PrintWriter pw = new PrintWriter(new File(genFile), "utf8");
		Template template = config.getTemplate(tempFile);
		template.process(mateDate, pw);
		// template.process(mateDate, pw);

	}
}
